package planit.view;

import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import planit.model.Event;
import planit.model.Model;
import planit.util.ExtendedDate;


@SuppressWarnings("serial")
public class SchedulePaneWeek extends SchedulePane {
	private int[] columnsPerWeekday;
	
	public SchedulePaneWeek(Model model) {
		super(ExtendedDate.createDate(), 7, model);
	}
	
	protected void addAllEvents() {
		setEvents(model.getSchedule().getEvents(this.getStartDate(), ExtendedDate.dateWithAddedDays(this.getStartDate(), days)));
		collisions = new HashMap<Event, ArrayList<Event>>();
		columnsPerWeekday = new int[]{1,1,1,1,1,1,1};
		Date tempDate = getStartDate();
		int temp = 1;
		for (int n = 1; n < 8; n++) {
			tempDate = ExtendedDate.dateWithAddedDays(getStartDate(), n);
			for (Event a : events) {
				if (ExtendedDate.isSameDay(a.getStartTime(), tempDate)) {
					collisions.put(a, new ArrayList<Event>());
					for (Event b : events) {
						if (!a.equals(b)) {
							if (a.getStartTime().getTime() >= b.getEndTime()
									.getTime()
									|| a.getEndTime().getTime() <= b
											.getStartTime().getTime()) {
							} else {
								collisions.get(a).add(b);
								temp++;
							}
						}
					}
					columnsPerWeekday[n-1] = Math.max(columnsPerWeekday[n-1], temp);
					temp = 1;
				}
			}
		}
		this.repaint();
	}
	
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		int col = 0;
		int pos = 0;
		for (int n = 1; n < 8; n++) {g.setColor(Color.BLACK);
			g.setColor(Color.BLACK);
			g.drawLine(n*this.getWidth()/7, 0, n*this.getWidth()/7, this.getHeight());
			col = 0;
			
			for (Event e : events) {
				cal.setTime(e.getStartTime());
				pos = minutesToHeight(cal.get(Calendar.MINUTE)
						+ cal.get(Calendar.HOUR_OF_DAY) * 60);
				if (ExtendedDate.isSameDay(e.getStartTime(), ExtendedDate.dateWithAddedDays(getStartDate(), n-1))) {
					/*if (collisions.get(e).size() > 0) {
						drawEvent(g, e,
								col * ((this.getWidth()/7) / columnsPerWeekday[n-1]) + (this.getWidth()/7)*n, pos,
								minutesToHeight(e.getDuration()),
								this.getWidth() / columnsPerWeekday[n-1]);
						col++;
					} else {*/
						drawEvent(g, e, (n-1)*this.getWidth()/7, pos,
								minutesToHeight(e.getDuration()),
								this.getWidth()/7);
					//}
				}
			}
		}
	}
	
    protected void drawEvent(Graphics g, Event e, int startX, int startY, int height, int width) {
		//g.setColor(Color.BLACK);
		//g.fillRect(startX, startY, width, minutesToHeight(e.getDuration()));
		g.setColor(Color.BLUE);
		g.fillRect(startX, startY/*+2*/, width/*-4*/, minutesToHeight(e.getDuration())/*-4*/);
		g.setColor(Color.WHITE);
		g.drawString(e.getName(), startX+6, startY+13);
    }
}
